<!--
 * @Author: Wangtao
 * @Date: 2020-09-21 09:55:09
 * @LastEditors: zhanwang
 * @LastEditTime: 2021-08-13 15:11:32
-->
<template>
  <div class="telephone-satisfaction">
    <div class="warn-text"><span class="el-icon-info"></span>设置呼入或外呼通话结束时，是否座席挂机自动触发满意度调查。呼入和外呼通话时，点击电话工具条满意度调查按钮，都可以直接发起满意度调查。</div>
    <p class="statis-title title-one">自动满意度</p>
    <el-checkbox v-model="form.autoIn">呼入</el-checkbox>
    <el-checkbox v-model="form.autoOut">外呼</el-checkbox>
    <p class="statis-title">设置</p>
    <div class="warn-text" style="margin:20px 0 30px" v-if="!isBegin"><span class="el-icon-info"></span>1、放音结束后通话会自动挂机 2、未选择播放语音时，系统将在收集用户输入后用自动挂机</div>
    <div class="clearfix config-box">
      <ul class="statis-left fl">
        <li :class="isBegin? 'statis-active': ''"><span class="statis-span" @click="showStatis(true)" >满意度语音播报</span></li>
        <li :class="!isBegin? 'statis-active': ''"><span class="statis-span" @click="showStatis(false)" >满意度结束</span></li>
      </ul>
      <div class="statis-right fl" v-show="isBegin">
        <el-form class="m7-form" :model="form" label-position="top" size="mini">
          <el-form-item label="播放语音" prop='voicePlayConfig.voiceId' :rules="[{ required: true, message: '必填', trigger: 'change' }]" >
            <el-select v-model="form.voicePlayConfig.voiceId" size="mini" filterable placeholder="请选择" style="width:314px;margin-right:10px;" @change='changeVoice'>
              <el-option
                      v-for="item in getVoiceLibraryList"
                      :key="item._id"
                      :label="item.name"
                      :value="item._id">
              </el-option>
            </el-select>
            <AudioProgress :url="recordFile" :showListen="true" type="common" :row="{_id: 'satisfaction_begin', audioDuration: audioDuration}" ref="audioRef" v-show="isBegin" :showDowload="false"></AudioProgress>
          </el-form-item>
          <div class="clearfix">
            <el-form-item prop="voicePlayConfig.replayTimes" style="width:150px; margin-right:14px;float:left" :rules="[{ required: true, validator: validateTimes, trigger: 'blur' }]">
                <span slot="label">
                    重播次数
                   <el-tooltip class="item" effect="dark" content="话术录音最多重复播放的次数，到达次数后客户未正确响应则挂机，次数为2则播放3次，默认为2" placement="top">
                      <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42 tip-span"></span>
                   </el-tooltip>
                </span>
              <el-input  v-model="form.voicePlayConfig.replayTimes" size="mini">
                <span slot="suffix">次</span>
              </el-input>
            </el-form-item>
            <el-form-item prop="voicePlayConfig.replayInterval" style="width:150px;float:left" :rules="[{ required: true, validator: validateInterval, trigger: 'blur' }]">
                <span slot="label">
                    重播间隔
                   <el-tooltip class="item" effect="dark" content="语音播放重复间隔的时间，到达间隔时间后客户未正确响应则重播，最小时间为1秒，建议最大时间不超过5秒" placement="top">
                      <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42 tip-span"></span>
                   </el-tooltip>
                </span>
              <el-input  v-model="form.voicePlayConfig.replayInterval" size="mini">
                <span slot="suffix">秒</span>
              </el-input>
            </el-form-item>
          </div>
          <el-form-item label="按键" prop='voicePlayConfig.next' :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
            <div v-for="(item, index) in form.voicePlayConfig.next" :key="index" class="clearfix key-box">
              <m7Select style="width:108px" class="fl" filterable  size="mini" v-model="item.key" placeholder="请选择" :options="keyList"></m7Select>
              <el-input v-model.trim="item.value" placeholder="请输入内容" class="fl" size="mini" style="width:200px;margin-left:10px"></el-input>
              <span class="V7_iconfont V7_iconV7tubiao-109 delete-span" v-if="form.voicePlayConfig.next.length !== 1" @click="addOrDeleteKey(index, 'delete')"></span>
              <span class="V7_iconfont V7_iconV7tubiao_xinzeng-104 add-span" v-if="index === form.voicePlayConfig.next.length - 1 && form.voicePlayConfig.next.length !== 11"  @click="addOrDeleteKey(index, 'add')"></span>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="statis-right fl" v-show="!isBegin">
        <el-form class="m7-form" :model="form" label-position="top" size="mini">
          <el-form-item label="播放语音" prop='endConfig.voiceId' :rules="[{ required: true, message: '必填', trigger: 'change' }]" >
            <el-select v-model="form.endConfig.voiceId" size="mini" filterable placeholder="请选择" style="width:314px;margin-right:10px" @change='changeVoice'>
              <el-option
                      v-for="item in getVoiceLibraryList"
                      :key="item._id"
                      :label="item.name"
                      :value="item._id">
              </el-option>
            </el-select>
            <AudioProgress :url="recordFile" :showListen="true" type="common" ref="audioEndRef" :row="{_id: 'satisfaction_end', audioDuration: audioDuration}" v-show="!isBegin" :showDowload="false"></AudioProgress>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="moreBtn">
      <el-button size="mini" type="primary" @click="save">确定</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Mixins } from 'vue-property-decorator'
import { deepClone } from '@/utils/common'
import { IvrModule } from '@/store/modules/config/ivr'
import AudioProgress from '@/components/audio/AudioProgress.vue'
import uniqBy from 'lodash/uniqBy'
import findIndex from 'lodash/findIndex'
import handleOprateMixin from '@/components/configCommon/mixins/handleOperate'
interface FormData {
  autoIn: boolean
  autoOut: boolean
  voicePlayConfig: any
  endConfig: any
}

@Component({
  name: 'TelephoneSatisfaction',
  components: { AudioProgress }
})

export default class extends Mixins(handleOprateMixin) {
  private recordFile: string = '' // 录音地址
  private audioDuration: number = 0 // 录音的总时长
  private isBegin: boolean = true // 当前是否是满意度开始节点
  private keyList = [ // 按键列表，不能重复
    {
      label: '按键1',
      value: '1'
    },
    {
      label: '按键2',
      value: '2'
    },
    {
      label: '按键3',
      value: '3'
    },
    {
      label: '按键4',
      value: '4'
    },
    {
      label: '按键5',
      value: '5'
    },
    {
      label: '按键6',
      value: '6'
    },
    {
      label: '按键7',
      value: '7'
    },
    {
      label: '按键8',
      value: '8'
    },
    {
      label: '按键9',
      value: '9'
    },
    {
      label: '按键0',
      value: '0'
    },
    {
      label: '按键#',
      value: '#'
    }
  ]

  private form: FormData = { // 初始化表单信息
    autoIn: false,
    autoOut: false,
    voicePlayConfig: {
      voiceId: '',
      replayTimes: 2,
      replayInterval: 3,
      next: [{ key: '1', value: '' }]
    },
    endConfig: {
      voiceId: ''
    }
  }

  private validateTimes = (rule: any, value: any, callback: any) => {
    if (value === '') {
      callback(new Error('请输入重播次数'))
    } else if (value) {
      if (!/^\d+$/.test(value)) {
        callback(new Error('重播次数必须为正整数'))
      } else if (value < 0 || value > 3) {
        callback(new Error('重播次数：0-3次'))
      } else {
        callback()
      }
    }
  }

  private validateInterval = (rule: any, value: any, callback: any) => {
    if (value === '') {
      callback(new Error('请输入重播间隔'))
    } else if (value) {
      if (!/^\d+$/.test(value)) {
        callback(new Error('重播间隔必须为正整数'))
      } else if (value < 1 || value > 10) {
        callback(new Error('重播间隔：1-10秒'))
      } else {
        callback()
      }
    }
  }

  private options: object[] = [] // 录音文件的下拉

  private showStatis (begin: boolean) { // 满意度开始和结束点击切换
    if (begin) { // restStatus 是重置录音组件内的进度，定时器之类的
      (this as any).$refs.audioEndRef.restStatus()
    } else {
      (this as any).$refs.audioRef.restStatus()
    }
    this.isBegin = begin
    const id = this.isBegin ? this.form.voicePlayConfig.voiceId : this.form.endConfig.voiceId
    this.changeVoice(id) // 点击切换的时候，要把之前的最新的信息更新到audio
  }

  private addOrDeleteKey (index: number, type: string) { // 新增或删除按键
    if (type === 'add') {
      this.form.voicePlayConfig.next.push({ key: '', value: '' })
    } else {
      this.form.voicePlayConfig.next.splice(index, 1)
    }
  }

  private changeVoice (data: string) { // 更换录音时，要把最新的地址放到根部的audio
    const currentVoice = this.filterVoice(data)
    this.recordFile = currentVoice[0] ? currentVoice[0].fileUrl : ''
    this.audioDuration = currentVoice[0] ? currentVoice[0].audioDuration : 0
  }

  private handleFrom () { // 提交表单前的表单校验
    const nextArr = this.form.voicePlayConfig.next || []
    const keyArr = uniqBy(nextArr, 'key') // 按照key排重
    const valueArr = uniqBy(nextArr, 'value') // 按照value排重
    const keyIndex = findIndex(nextArr, ['key', ''])
    const valueIndex = findIndex(nextArr, ['value', ''])
    let flag = false
    this.validateTimes(null, this.form.voicePlayConfig.replayTimes, (value) => {
      if (value) {
        this.$message({ message: value.message, type: 'error' })
        flag = true
      }
    })
    this.validateInterval(null, this.form.voicePlayConfig.replayInterval, (value: any) => {
      if (value) {
        this.$message({ message: value.message, type: 'error' })
        flag = true
      }
    })
    if (flag) {
      return false
    }
    if (keyIndex >= 0) {
      this.$message({ message: '按键不能为空', type: 'error' })
      return false
    } else if (valueIndex >= 0) {
      this.$message({ message: '按键内容不能为空', type: 'error' })
      return false
    } else if (keyArr.length !== nextArr.length) {
      this.$message({ message: '按键不能重复', type: 'error' })
      return false
    } else if (valueArr.length !== nextArr.length) {
      this.$message({ message: '按键内容不能重复', type: 'error' })
      return false
    } else {
      return true
    }
  }

  private filterVoice (id: string) {
    return deepClone(this.getVoiceLibraryList).filter(item => item._id === id)
  }

  private save () { // 保存满意度
    if (!this.handleFrom()) { // 保存之前校验表单，排重
      return false
    }
    const actionData = this.form
    const data = { url: '/call/action/ivr/phoneSatisfaction/save', method: 'POST', data: actionData }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      if (res && res.success) {
        this.$message({ message: '保存成功', type: 'success' })
      }
    })
  }

  get getVoiceLibraryList () {
    return this.$store.state.common.publicCache.voiceLibraryList || []
  }

  private beforeMount () { // 初始化获取语音库列表和满意度信息查询
    const p2 = IvrModule.IvrCommonAction({ url: '/call/action/ivr/phoneSatisfaction/query', method: 'POST', data: {} })
    Promise.all([p2]).then(([statisRes]) => {
      if (statisRes && statisRes.success && statisRes.data) {
        Object.keys(statisRes.data).forEach(key => {
          if (this.form[key] !== undefined) {
            this.form[key] = statisRes.data[key]
          }
        })
      }
      this.$getCache('/call/action/general/query', ['voiceLibraryList'], false).then((data: any) => {
        this.showStatis(true)
      })
    })
  }
}
</script>

<style lang="stylus" scoped>
  .telephone-satisfaction
    height calc(100% - 40px)
    box-shadow 0px 0px 3px 0px #E0E5F0, 0px 1px 4px 0px #E0E5F0
    border-radius 10px
    padding 16px
    overflow auto
    .warn-text
      background $bgc-reminder
      padding 14px
      border-radius 4px
      .el-icon-info
        color $c-warn
        padding-right 6px
        font-size 14px
        vertical-align middle
    .statis-title
      color $fc-gray
      margin-top 20px
      font-size 14px
    .title-one
      margin-bottom 6px
    .config-box
      margin-top 20px
    .statis-left
      width 200px
      margin-top 10px
      li
        height 44px
        position relative
        border-left 1px solid $c-main
        color $fc-gray
        cursor pointer
        &:last-child
          border 0
        &:before
          content ''
          width 6px
          height 6px
          display inline-block
          border-radius 50%
          background-color $icon-gray
          position absolute
          left -3px
          top -5px
        .statis-span
          position absolute
          top -9px
          left 10px
      .statis-active
         &:before
          background-color $c-main
         .statis-span
           color $c-main
    .statis-right
       .tip-span
          color $icon-gray
          font-size 12px
          cursor pointer
       .audio-span
          background $c-main
          color #fff
          font-size 12px
          line-height 20px
          display inline-block
          width 20px
          height 20px
          text-align center
          border-radius 50%
          vertical-align middle
          margin-left 10px
          cursor pointer
       .delete-span,.add-span
          color $icon-gray
          cursor pointer
          margin-left 10px
          display inline-block
       .delete-span
         &:hover
           color $c-danger
       .add-span
          color $c-main
          margin-left 10px
       .key-box
         margin-bottom 20px
  .moreBtn
    position absolute
    bottom 20px
    right 20px
</style>
